import os
import json
import glob
from fastmcp import Client

class MCPConfigLoader:
    """MCP配置加载器"""
    
    def __init__(self, config_dir=None):
        """初始化MCP配置加载器
        
        Args:
            config_dir (str): 配置文件目录，默认为当前文件所在目录
        """
        self.config_dir = config_dir or os.path.dirname(__file__)
        self.configs = {}
        self.clients = []
        
    def load_all_configs(self):
        """加载MCP配置文件"""
        # 只加载 mcp-config.json 文件
        config_file = os.path.join(self.config_dir, 'mcp-config.json')
        self.configs = {}
        
        if os.path.exists(config_file):
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 获取文件名作为配置标识
                    config_name = os.path.basename(config_file)
                    self.configs[config_name] = config
                    print(f"成功加载配置文件: {config_name}")
            except Exception as e:
                print(f"加载配置文件 {config_file} 时出错: {e}")
        else:
            print(f"配置文件 {config_file} 不存在")
        
        return self.configs
    
    def initialize_clients(self):
        """初始化所有MCP客户端"""
        self.clients = []
        for config_name, config in self.configs.items():
            if 'mcpServers' in config:
                for server_name, server_config in config['mcpServers'].items():
                    try:
                        client = Client(server_config['url'])
                        self.clients.append({
                            'config_name': config_name,
                            'server_name': server_name,
                            'client': client
                        })
                        print(f"成功初始化MCP客户端: {config_name}:{server_name}")
                    except Exception as e:
                        print(f"初始化MCP客户端 {config_name}:{server_name} 时出错: {e}")
        
        return self.clients
    
    def get_configs(self):
        """获取所有配置"""
        return self.configs
    
    def get_clients(self):
        """获取所有客户端"""
        return self.clients

# 用于直接运行的函数
def load_mcp_configs_and_clients(config_dir=None):
    """加载所有MCP配置并初始化客户端
    
    Returns:
        tuple: (configs, clients)
    """
    loader = MCPConfigLoader(config_dir)
    configs = loader.load_all_configs()
    clients = loader.initialize_clients()
    return configs, clients

if __name__ == "__main__":
    # 测试代码
    configs, clients = load_mcp_configs_and_clients()
    print(f"加载了 {len(configs)} 个配置文件")
    print(f"初始化了 {len(clients)} 个客户端")